package cn.icyzx.service;

import cn.icyzx.dao.DaoUser;
import cn.icyzx.dao.SendMail;
import cn.icyzx.models.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpSession;

import static cn.icyzx.util.StaticConstUtil.*;


/**
 * Created by 郑凯 on 2016/7/18.
 */
@Service
@Transactional
public class LoginService {

    @Autowired
    private DaoUser daoUser;

    @Autowired
    private SendMail sendMail;

    /**
     * login
     *
     * @param session 设置登陆后用户存在的时长
     * @return java.lang.String 根据不同的返回值，来判断登陆的状态
     */
    public String login(String usernameOrEmail, String password, HttpSession session) {

        if (!(daoUser.isExistName(usernameOrEmail) || daoUser.checkEmail(usernameOrEmail)))
            return LOGIN__NAME_NOT_EXIST;


        User curUser = daoUser.login(usernameOrEmail, password);
        if (curUser != null) {
            if (!daoUser.checkActive(curUser.getUid()))
                return LOGIN_EMAIL_FAIL;

            session.setAttribute("user", curUser);
            session.setMaxInactiveInterval(USER_EXIST_TIME);
            return LOGIN_SUCCESS;
        }

        return LOGIN_FAIL;
    }

    /**
     * register
     *
     * @param user 封装好的user(包含username,password,email)
     * @return java.lang.String 注册进度信息
     */
    public String register(User user) {

        if (!daoUser.register(user))
            return REGISTER_FAIL;

        else if (sendMail.sendMailToActive(user))
            return REGISTER_SUCCESS;

        else return REGISTER_EMAIL_FAIL;
    }


    public boolean checkName(String username) {
        return daoUser.isExistName(username);
    }

    public boolean checkEmail(String email) {
        return daoUser.checkEmail(email);
    }


}
